require 'View/UIBase/UIBase'

UICharactorInfoHeroRuneRefine = UIBase.New(PanelNames.UICharactorInfoHeroRuneRefine)
local this = UICharactorInfoHeroRuneRefine
local runeInfo = nil
local m_cur_list  = nil
local m_selected_list = {}

function UICharactorInfoHeroRuneRefine.Init(runeInfoParam)
   runeInfo = runeInfoParam
    UIBase.Init(UICharactorInfoHeroRuneRefine)
end

local sort_func = function(a,b)
    if a.quality ~= b.quality then
        return a.quality < b.quality
    else
        if a.level and b.level and a.level ~= b.level then
            return a.level < b.level
        end
    end
    return tonumber(a.itemModelId) > tonumber(b.itemModelId)
end

function UICharactorInfoHeroRuneRefine:OnCreate()
    self.btn_levelup    = self:GetChild("btn_refine")
    self.btn_Help       = self:GetChild("help")
    self.inlayItem      = self:GetChild("EquipItem")
    self.txt_name       = self:GetChild("name")
    self.txt_power      = self:GetChild("n88"):GetChild("num1")
    self.scroll_list    = self:GetChild("itemList")
    self.ctr_nothing    = self:GetController("nothing")
    self.slider         = self:GetChild("Slider")
    self.txt_sliderNum  = self:GetChild("sliderNum")
    self.curLevel       = self:GetChild("level")
    self.comPreLevel    = self:GetChild("upnumGroup")
    self.txtPreLevel    = self:GetChild("upnum")
    self.effectLevelUp         = self:GetChild("effect_zbjl").wrapTarget
    self.txtMoneyNum = self:GetChild("useNum")
    self.txt_name.text = runeInfo.name
    self.tabAttr = {}
    for i = 1,4 do
        local attr = self:GetChild("attri"..i);
        attr.visible = false
        table.insert(self.tabAttr, attr)
    end
    m_cur_list = self:GetStuffList()
    self:RefreshArr()
end

function UICharactorInfoHeroRuneRefine:AddEvent()
    self:RegisterOnClick(self:GetChild("btn_refine"), self.OnClick_levelup)
    self:RegisterOnClick(self:GetChild("btn_choose"), self.OnClick_quickChoose)
    self:RegisterOnClick(self:GetChild("bgclose"), self.OnClick_close)
    self:RegisterOnClick(self.btn_Help, self.OnClickHelp)
    self:RegisterEvent(Config.EventType.FreshHeroRuneLevelUp,self.LevelUpRefresh)
end

function UICharactorInfoHeroRuneRefine:OnUpgradeLevel()
    AudioManager.Play(2015)
    self:Refresh()
    self:RefreshArr()
    Util.PlayAction(self.effectLevelUp, "idle", false)
end

local m_attr_list
function UICharactorInfoHeroRuneRefine:RefreshArr(config)
    runeInfo = logicMgr.RuneManager.GetHeroRuneSrvInfo(runeInfo.partnerId, runeInfo.index)
    local curBaseAttrData = runeInfo["baseAttr"]
    for k,v in pairs(curBaseAttrData) do
        local item = self.tabAttr[k]
        if item == nil then
            break
        end
        item.visible = true
        local title = item:GetChild("title")
        local attrValue = item:GetChild("num1");
        local attrImage = item:GetChild("image1");
        local attrPre = item:GetChild("pre1");
        local attrPreValue = item:GetChild("preNum1");
        attrImage.url = "ui://ICONAtlas/attr" .. k;

        local attrName = getLanguage(string.format(Config.LangAttribute,v[1]));
        title.text = attrName
        attrValue.text = v[2]
        if config then
            attrPre.visible = true
            local nextBaseAttrData = config["f_BaseAttr"][k]
            attrPreValue.text = "+".. nextBaseAttrData[2]
        else
            attrPre.visible = false;
        end
    end
    if config then
        self.comPreLevel.visible = true
        self.txtPreLevel.text = config.f_Strengthen_lv
    else
        self.comPreLevel.visible = false
    end
end

--初始化物品信息
function UICharactorInfoHeroRuneRefine.SetData(index,obj)
    local item = CtrlManager.GetCtrl(PanelNames.Item)
    obj:GetController("select").selectedIndex = 1
    local ctr_select = obj:GetController("choose")
    local txt_num = obj:GetChild("num")
    if item ~= nil then
        local runeInfo = m_cur_list[index + 1]
        if runeInfo.itemType == EnumConst.ItemTypeEnum.Rune then
            logicMgr.RuneManager.SetRuneItemData(obj, runeInfo, true)
        else
            item.initData(obj, runeInfo, 1, false)
        end
        if m_selected_list[runeInfo.itemId] then
            ctr_select.selectedIndex = 1
            if runeInfo.Num then
                txt_num.text = table.concat({getNumString(runeInfo.Num) , "/", getNumString(runeInfo.num) })
            else
                txt_num.text = ""
            end
        else
            ctr_select.selectedIndex = 0
        end

        obj.onClick:Clear()
        obj.onClick:Add(function()
            UICharactorInfoHeroRuneRefine:OnSelectItem(runeInfo, obj)
        end)
    end
end

function UICharactorInfoHeroRuneRefine:OnSelectItem(rune, obj)
    local ctr_select = obj:GetController("choose")
    local txt_num = obj:GetChild("num")

    local isMax = logicMgr.RuneManager.GetRuneLevelUpCost(runeInfo.itemModelId, runeInfo.level)
    if isMax == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    end
    local select_exp = runeInfo.exp
    local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
    local need = isMax - (select_exp+orginalExp-logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level))

    if m_selected_list[rune.itemId] then
        if rune.itemType == EnumConst.ItemTypeEnum.Rune then
            local num = m_selected_list[rune.itemId].Num
            if num > 1 then
                m_selected_list[rune.itemId].Num = num - 1
                txt_num.text = table.concat({getNumString(m_selected_list[rune.itemId].Num) , "/", getNumString(m_selected_list[rune.itemId].num) })
            else
                txt_num.text = m_selected_list[rune.itemId].num
                m_selected_list[rune.itemId] = nil
                ctr_select.selectedIndex = 0
            end
        else
            local num = m_selected_list[rune.itemId].Num
            if num > 1 then
                m_selected_list[rune.itemId].Num = num - 1
                txt_num.text = table.concat({getNumString(m_selected_list[rune.itemId].Num) , "/", getNumString(m_selected_list[rune.itemId].num) })
            else
                txt_num.text = m_selected_list[rune.itemId].num
                m_selected_list[rune.itemId] = nil
                ctr_select.selectedIndex = 0
            end
        end
    else
        local count = 0
        if rune.itemType == EnumConst.ItemTypeEnum.Rune then
            local cfgData = logicMgr.RuneManager.GetRuneCfgInfo(rune.itemModelId, rune.level)
            count = math.ceil(need / (cfgData.f_BaseExp))
        else
            count = math.ceil(need/ (rune.itemFunction[2]))
        end
        if count > rune.num then
            rune.Num = rune.num
        else
            rune.Num = count
        end
        m_selected_list[rune.itemId] = rune
        ctr_select.selectedIndex = 1
        txt_num.text = table.concat({getNumString(m_selected_list[rune.itemId].Num) , "/", getNumString(m_selected_list[rune.itemId].num) })
    end

    local sk_config = nil
    select_exp = select_exp - runeInfo.exp
    for _,v in pairs(m_selected_list) do
        if v.itemType == EnumConst.ItemTypeEnum.Rune then
            sk_config = logicMgr.RuneManager.GetRuneCfgInfo(v.itemModelId, v.level)
            if sk_config then
                select_exp = select_exp + sk_config.f_BaseExp * v.Num
            end
        else
            if v.itemFunction then
                select_exp = select_exp + v.Num * v.itemFunction[2]
            end
        end
    end
    UICharactorInfoHeroRuneRefine:OnSelectExpChanged(select_exp)
end

function UICharactorInfoHeroRuneRefine:OnSelectExpChanged(selectExp)
    local isMax = logicMgr.RuneManager.GetRuneLevelUpCost(runeInfo.itemModelId, runeInfo.level)
    if isMax == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
    else
        --local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
        --local need = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level+1) - orginalExp
        local select_exp = runeInfo.exp
        local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
        local need = isMax - (select_exp+orginalExp-logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level))
        local runeCfg = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, runeInfo.level)
        local sk_config = nil
        local remainExp = selectExp
        local totalCoinCost = 0
        if selectExp >= need then
            local nextlv = runeInfo.level + 1
            totalCoinCost = need * runeCfg.f_GoldCo
            remainExp = selectExp - need
            sk_config = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, nextlv)
            if sk_config then
                local count = 100
                while sk_config and remainExp >= sk_config.f_CostExp do
                    local tsk_config = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, nextlv + 1)
                    if tsk_config then
                        if remainExp >= sk_config.f_CostExp then
                            nextlv = nextlv + 1
                            totalCoinCost = totalCoinCost + (sk_config.f_CostExp * sk_config.f_GoldCo)
                            remainExp = remainExp - sk_config.f_CostExp
                            sk_config = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, nextlv)
                        end
                    else
                        break
                    end
                    --nextlv = nextlv + 1
                    --totalCoinCost = totalCoinCost + (tsk_config.f_CostExp * tsk_config.f_GoldCo)
                    --remainExp = remainExp - sk_config.f_CostExp
                    --sk_config = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, nextlv)

                    count = count - 1
                    if count < 0 then
                        break
                    end
                end
                sk_config = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, nextlv)
                totalCoinCost = totalCoinCost + remainExp * sk_config.f_GoldCo
                if sk_config then
                    self:RefreshArr(sk_config)
                end
            else
                self:RefreshArr()
            end
        else
            self:RefreshArr()
            totalCoinCost = selectExp * runeCfg.f_GoldCo
        end
        local showExp = selectExp + runeInfo.exp
        self.slider.value = (showExp / (need + runeInfo.exp)) * 100
        self.txt_sliderNum.text = showExp .. "/" .. need + runeInfo.exp
        self:RefreshCostCoin(totalCoinCost)
    end
end

function UICharactorInfoHeroRuneRefine:RefreshCostCoin(totalCost)
    local runeCfg = logicMgr.RuneManager.GetRuneCfgInfo(runeInfo.itemModelId, runeInfo.level)
    if runeCfg then
        --local totalCost = totalExp* runeCfg.f_GoldCo
        local money = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MONEY);
        if totalCost > money then
            money = string.TextColor(getNumString(money),"#FF0000")
        else
            money = getNumString(money)
        end
        local text = getNumString(totalCost) .. "/" .. money
        self.txtMoneyNum.text = text
    end
end

function UICharactorInfoHeroRuneRefine:OnEnable()
    self:AddEvent()
    m_selected_list = {}
    self:Refresh()
end

function UICharactorInfoHeroRuneRefine:LevelUpRefresh()
    AudioManager.Play(2015)
    Util.PlayAction(self.effectLevelUp, "idle", false)
    self:Refresh()
    self:RefreshArr()
end

function UICharactorInfoHeroRuneRefine:Refresh()
    m_selected_list = {}
    runeInfo = logicMgr.RuneManager.GetHeroRuneSrvInfo(runeInfo.partnerId, runeInfo.index)
    self.txt_name.text = runeInfo.name
    self.txt_power.text = runeInfo.power
    self.curLevel.text = runeInfo.level
    self.comPreLevel.visible = false
    local item = CtrlManager.GetCtrl(PanelNames.Item)
    if item ~= nil then
        logicMgr.RuneManager.SetRuneItemData(self.inlayItem, runeInfo, true)
        self.inlayItem.onClick:Clear()
    end
    local money = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MONEY);
    self.txtMoneyNum.text = "0/" .. getNumString(money)
    local need = logicMgr.RuneManager.GetRuneLevelUpCost(runeInfo.itemModelId, runeInfo.level)
    local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
    local total = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level+1)- orginalExp
    if need == 0 then
        self.btn_levelup.grayed = true
        self.slider.value = 100
        self.txt_sliderNum.text = runeInfo.exp
    else
        self.slider.value = (runeInfo.exp / total) * 100
        self.txt_sliderNum.text = runeInfo.exp .. "/" .. total
    end

    m_cur_list = self:GetStuffList()

    if #m_cur_list == 0 then
        self.ctr_nothing.selectedIndex = 1
        self.scroll_list.numItems = 0
    else
        self.ctr_nothing.selectedIndex = 0
        self.scroll_list.itemRenderer = this.SetData

        self.scroll_list:SetVirtual()
        self.scroll_list.numItems = #m_cur_list
    end
    self:RefreshArr()
end

function UICharactorInfoHeroRuneRefine:OnClick_close()
    closeUI(PanelNames.UICharactorInfoHeroRuneRefine)
end

function UICharactorInfoHeroRuneRefine:OnClickHelp()
    local txts = {}
    txts["title"] = "RuneLevelUpTitle"
    txts["des"] = "RuneLevelUp"
    showUI(PanelNames.CommonTips, txts)
end

function UICharactorInfoHeroRuneRefine:OnClick_levelup()
    local isPop = nil
    local need = logicMgr.RuneManager.GetRuneLevelUpCost(runeInfo.itemModelId, runeInfo.level)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    else
        if table.getn(m_selected_list) == 0 then
            UISysTips.AddMsg(getLanguage("DebrisText25"))
            return
        end
    end

    local list = {}
    for k,v in pairs(m_selected_list) do
        if v.itemType == 10 and v.quality >=8 then
            isPop = true
        end
        table.insert(list, {itemid = tonumber(v.itemId), modelid = v.itemModelId, num = v.Num})
    end

    if #list > 0 then
        if isPop then
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            pop.Init("135",function(b)
                if b then
                    runeHandler.reqUpRuneLv(runeInfo.partnerId, runeInfo.itemId, runeInfo.index, list)
                end
            end)
        else
            runeHandler.reqUpRuneLv(runeInfo.partnerId, runeInfo.itemId, runeInfo.index, list)
        end
    end
end

function UICharactorInfoHeroRuneRefine:OnClick_quickChoose()
    if #m_cur_list == 0 then
        return
    end
    m_selected_list = {}
    --local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
    --local need = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level+1) - orginalExp
    --if need == 0 then
    --    UISysTips.AddMsg(getLanguage("DebrisText24"))
    --    return
    --end

    local isMax = logicMgr.RuneManager.GetRuneLevelUpCost(runeInfo.itemModelId, runeInfo.level)
    if isMax == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    end
    local curExp = runeInfo.exp
    local orginalExp = logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, 0)
    local need = isMax - (curExp+orginalExp-logicMgr.RuneManager.GetRuneBaseExp(runeInfo.itemModelId, runeInfo.level))

    local expnum = 0
    local sk_config = nil
    for k,v in pairs(m_cur_list) do
        if v.itemId ~= runeInfo.itemId then
            if v.lock ~= 1 then
                if v.itemType == EnumConst.ItemTypeEnum.Rune then
                    sk_config = logicMgr.RuneManager.GetRuneCfgInfo(v.itemModelId, v.level)
                    if sk_config then
                        local count = math.ceil(need / sk_config.f_BaseExp)
                        if count > v.num then
                            v.Num = v.num
                        else
                            v.Num = count
                        end
                        expnum = expnum + sk_config.f_BaseExp * v.Num
                    end
                else
                    local count = math.ceil(need / v.itemFunction[2])
                    if count > v.num then
                        v.Num = v.num
                    else
                        v.Num = count
                    end
                    expnum = expnum + v.itemFunction[2] * v.Num
                end

                m_selected_list[v.itemId] = v
                if expnum >= need then
                    break
                end
            end
        end
    end
    UICharactorInfoHeroRuneRefine:OnSelectExpChanged(expnum)

    self.scroll_list.numItems = #m_cur_list
end

function UICharactorInfoHeroRuneRefine:OnDisable()
end

function UICharactorInfoHeroRuneRefine:GetStuffList()
    local list = clone(logicMgr.RuneManager.GetStuffRuneList())
    table.sort(list, sort_func)
    local it1 = ItemManager.getItemIdByModelId(200049)
    local it2 = ItemManager.getItemIdByModelId(200050)
    if it2 then
        table.insert(list, 1, clone(logicMgr.ItemManager.getItemData(it2)))
    end
    if it1 then
        table.insert(list, 1, clone(logicMgr.ItemManager.getItemData(it1)))
    end
    return list
end

return UICharactorInfoHeroRuneRefine